﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hengbei.BLL;

namespace Hengbei.Web
{
    public partial class UserManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void dvUser_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            gvUsers.DataBind();
        }

        protected void dvUser_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            string loginID = e.Values["LoginID"].ToString().Trim();
            if (UserService.IfUserLoginIDExists(loginID))
            {
                e.Cancel = true;
                Page.RegisterStartupScript("LoginIDAlert", "<script language=javascript>alert(\"登录名已经存在！\")</script>");
            }

            if (e.Values["BirthDate"] != null)
            {
                string birthdate = e.Values["BirthDate"].ToString().Trim();
                DateTime d = new DateTime();
                if (!DateTime.TryParse(birthdate, out d))
                {
                    e.Cancel = true;
                    Page.RegisterStartupScript("BirthDateAlert", "<script language=javascript>alert(\"生日格式不正确！请输入如  1989-06-13   的生日值。\")</script>");
                }
            }

            if (e.Values["Age"] != null)
            {
                string age = e.Values["Age"].ToString().Trim();
                int i = 0;
                if (!int.TryParse(age, out i))
                {
                    e.Cancel = true;
                    Page.RegisterStartupScript("BirthDateAlert", "<script language=javascript>alert(\"年龄格式不正确！请输入整数数值。\")</script>");
                }
            }
        }

        /// <summary>
        /// If the gridview has a command field where showdeletebutton is true, then 
        /// it add a confirm message. 
        /// This function should be called in the RowDataBound event
        /// </summary>
        public static void AddConfirmDelete(GridView gv, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                foreach (DataControlField dcf in gv.Columns)
                {
                    if (dcf.ToString() == "CommandField")
                    {
                        if (((CommandField)dcf).ShowDeleteButton == true)
                        {
                            e.Row.Cells[gv.Columns.IndexOf(dcf)].Attributes
                            .Add("onclick", "return confirm(\"确认要删除该条记录吗？\")");
                        }
                    }
                }
            }
        }

        protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            AddConfirmDelete((GridView)sender, e);
        }
    }
}